/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.cketti.mailto.sample.slice;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import de.cketti.mailto.EmailIntentBuilder;
import de.cketti.mailto.sample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class MainAbilitySlice extends AbilitySlice {

    private Component mainContent;
    private TextField emailTo;
    private TextField emailCc;
    private TextField emailBcc;
    private TextField emailSubject;
    private TextField emailBody;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mainContent = findComponentById(ResourceTable.Id_main_content);
        emailTo = (TextField) findComponentById(ResourceTable.Id_email_to);
        emailCc = (TextField) findComponentById(ResourceTable.Id_email_cc);
        emailBcc = (TextField) findComponentById(ResourceTable.Id_email_bcc);
        emailSubject = (TextField) findComponentById(ResourceTable.Id_email_subject);
        emailBody = (TextField) findComponentById(ResourceTable.Id_email_body);
        Image img = (Image) findComponentById(ResourceTable.Id_img);
        findComponentById(ResourceTable.Id_button_send_email).setClickedListener(v -> sendEmail());
        final XPopup.Builder builder = new XPopup.Builder(getContext())
                .watchView(findComponentById(ResourceTable.Id_img));
        img.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                builder.asAttachList(new String[]{"Feedback"
                        }, null,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                sendFeedback();
                            }
                        })
                        .show();
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    private void sendFeedback() {
        boolean success = EmailIntentBuilder.from(this)
                .to(getEmail())
                .subject(getString(ResourceTable.String_feedback_subject))
                .body(getString(ResourceTable.String_feedback_body))
                .start();

        if (!success) {
            showToast(getString(ResourceTable.String_error_no_email_app));
        }
    }

    void sendEmail() {
        String to = emailTo.getText().toString();
        String cc = emailCc.getText().toString();
        String bcc = emailBcc.getText().toString();
        String subject = emailSubject.getText().toString();
        String body = emailBody.getText().toString();

        EmailIntentBuilder builder = EmailIntentBuilder.from(this);

        try {
            if (!TextTool.isNullOrEmpty(to)) {
                builder.to(to);
            }
            if (!TextTool.isNullOrEmpty(cc)) {
                builder.cc(cc);
            }
            if (!TextTool.isNullOrEmpty(bcc)) {
                builder.bcc(bcc);
            }
            if (!TextTool.isNullOrEmpty(subject)) {
                builder.subject(subject);
            }
            if (!TextTool.isNullOrEmpty(body)) {
                builder.body(body);
            }

            boolean success = builder.start();
            if (!success) {
                showToast(getString(ResourceTable.String_error_no_email_app));
            }
        } catch (IllegalArgumentException e) {
            String errorMessage = getString(ResourceTable.String_argument_error, e.getMessage());
            showToast(errorMessage);
        }
    }

    private void showToast(String str){
        ToastDialog toastDialog = new ToastDialog(getContext());
        toastDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toastDialog.setText(str);
        Text toastText=(Text) toastDialog.getComponent();
        if(toastText!=null)
        {
            toastText.setMultipleLine(true);
            toastText.setTextSize(14, Text.TextSizeType.FP);
            toastText.setPaddingBottom(20);
            toastText.setPaddingTop(20);
        }
        toastDialog.show();
    }

    public  String getEmail() {
        ohos.global.resource.ResourceManager resManager = getResourceManager();
        ohos.global.resource.RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/test.text");
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    rawFileEntry.openRawFile()));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


}
